package com.iwe3.protal.controller;

import com.iwe3.protal.Enum.SystemEnum;
import com.iwe3.protal.common.LoginResult;
import com.iwe3.protal.common.R;
import com.iwe3.protal.entity.UserEntity;
import com.iwe3.protal.service.IUserService;
import com.iwe3.protal.util.TokenUtil;
import com.iwe3.protal.view.LoginView;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@RequestMapping("/user")
@RestController
public class UserController {

    @Value("${token.signature}")
    private String signature;
    private final RedisTemplate redisTemplate;
    private final IUserService userServiceImpl;

    public UserController(@Qualifier("redisTemplate") RedisTemplate redisTemplate, IUserService userServiceImpl) {
        this.redisTemplate = redisTemplate;
        this.userServiceImpl = userServiceImpl;
    }

    //完整路径：user/login -> UserController # login()
    @PostMapping("/login")
    public R login(@RequestBody LoginView view, HttpServletRequest request){
        //调用业务层，查询数据库是否存在
        UserEntity user = userServiceImpl.login(view);
        if(Objects.isNull(user)){
            return R.fail(SystemEnum.LOGIN_ERROR);
        }

        //以前：user 放入到Session 作为登录标记
        //现在就使用：JWT 产生Token令牌
        Map<String,Object> params = new HashMap<>();
        params.put("sub",user.getId());
        params.put("iat",new Date());
        params.put("ip",getClientIp(request));
        String token = TokenUtil.createToken(params,signature);

        //采用Redis的String数据类型，存储：Token
        redisTemplate.opsForValue().set(token,"",30, TimeUnit.MINUTES);
        //令牌传递到前端

        return R.ok(new LoginResult(token,user.getNickname()));
    }

    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 如果通过了多个代理，那么X-Forwarded-For的值并不止一个，
        // 而是一串IP值，需要进行处理。
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0];
        }
        return ip;
    }

}
